package com.example.ruhun_verify

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.ContextCompat.startActivity
import com.cmic.gen.sdk.view.AuthLoginCallBack
import com.rich.oauth.callback.CheckboxCheckedChangeListener
import com.rich.oauth.callback.CheckboxUnCheckedClickListener
import com.rich.oauth.callback.InitCallback
import com.rich.oauth.callback.PreLoginCallback
import com.rich.oauth.callback.TokenCallback
import com.rich.oauth.core.RichAuth
import com.rich.oauth.core.UIConfigBuild
import com.rich.oauth.util.AuthConstants
import com.rich.oauth.util.RichLogUtil
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import org.json.JSONException
import org.json.JSONObject

/** RuhunVerifyPlugin */
class RuhunVerifyPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel
    private var context: Context? = null
    private var activity: Activity? = null
    private var authLoginCallBack: AuthLoginCallBack? = null
    private var carrier: String? = null//运营商类型

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        context = flutterPluginBinding.applicationContext
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "ruhun_verify")
        channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
        when (call.method) {
            "getPlatformVersion" -> {
                result.success("Android ${android.os.Build.VERSION.RELEASE}")
            }

            "getSimInfo" -> {
                carrier = RichAuth.getInstance().getOperatorType(context)
                result.success(hashMapOf(Pair("carrier", carrier?.toInt())))
            }

            "initLoginWithId" -> {
                val args = call.arguments as Map<*, *>
                val appId = args["id"] as String
//                var timeout = args["timeout"] as Int
                RichAuth.getInstance().init(context!!, appId, object : InitCallback {
                    override fun onInitSuccess() {
                        result.success(hashMapOf(
                                Pair("appId", appId)
                        ))
                    }

                    override fun onInitFailure(errorMsg: String) {
                        result.success(getMap(errorMsg))
                    }
                })

            }

            "preLoginWithBack" -> {
                //预登录
                preLogin(result)

            }

            "loginWithController" -> {
                val args = call.arguments as Map<*, *>
                val appName = args["appName"] as String
                //拉起授权页获取token
                if (activity == null) {
                    result.error("", "empty activity", null)
                } else {
                    result.success(emptyMap<Any, Any>())
                    getToken(activity!!, appName)
                }

            }

            "loginCheck" -> {
                val args = call.arguments as Map<*, *>
                val check = args["check"] as Boolean
                //拉起授权页获取token
                if (activity == null) {
                    result.error("", "empty activity", null)
                } else {
                    authLoginCallBack?.onAuthLoginCallBack(check)
                    result.success(emptyMap<Any, Any>())
                }
            }

            else -> {
                result.notImplemented()
            }
        }
    }

    private fun preLogin(result: Result) {
        activity?.let {
            RichAuth.getInstance().preLogin(it, object : PreLoginCallback {
                override fun onPreLoginSuccess() {
                    result.success(emptyMap<Any, Any>())
                }

                override fun onPreLoginFailure(errorMsg: String) {
                    result.success(getMap(errorMsg))
//                    RichLogUtil.e("预登录失败:$errorMsg")
//                Toast.makeText(this@MainActivity, "预登录失败：$errorMsg", Toast.LENGTH_SHORT).show()
                }
            })
        }
    }

    private fun getContentView(context: Context, resId: Int, appName: String): View {
        val relativeLayout = RelativeLayout(context)
        relativeLayout.layoutParams = RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT
        )
        val inflate =
                LayoutInflater.from(context).inflate(resId, relativeLayout, false) as RelativeLayout

        // 顶部导航栏返回按钮资源
        val ivReturn = inflate.findViewById<ImageView>(R.id.cmcc_ouath_navi_return)
        ivReturn.setOnClickListener {
            RichLogUtil.e("退出页面")
            RichAuth.getInstance().closeOauthPage()
            channel.invokeMethod(
                    "authViewDispose",
                    ""
            )
        }

        val appNameText = inflate.findViewById<TextView>(R.id.app_name_text)
        appNameText.text = appName;

        val appLogo= inflate.findViewById<ImageView>(R.id.cmcc_ouath_image_logo)
        if(appName == "入魂大集"){
            appLogo.setImageResource(R.drawable.app_logo_daji);
        }

        // 服务
        val cmccOuathStateText = inflate.findViewById<TextView>(R.id.cmcc_ouath_state_text)
        when (RichAuth.getInstance().getOperatorType(context)) {
            "1" -> cmccOuathStateText.text = "手机认证服务由中国移动提供"
            "2" -> cmccOuathStateText.text = "手机认证服务由中国联通提供"
            "3" -> cmccOuathStateText.text = "手机认证服务由中国电信提供"
        }
        val tvOtherWay = inflate.findViewById<View>(R.id.iv_code)
        tvOtherWay.setOnClickListener {
            RichAuth.getInstance().closeOauthPage()
            channel.invokeMethod(
                    "changeSmsLogin",
                    ""
            )
        }
        return inflate
    }

    private fun screenWidthDP(context: Context): Int {
        val dm = context.resources.displayMetrics
        return (dm.widthPixels / dm.density).toInt()
    }

    private fun screenHeightDP(context: Context): Int {
        val dm = context.resources.displayMetrics
        return (dm.heightPixels / dm.density).toInt()
    }

    private fun getToken(context: Activity, appName: String) {
        //一键登录
        val configBuild = UIConfigBuild.Builder()
        val contentView = getContentView(context, R.layout.oauth_root_view2,appName)
        val inputCode = contentView.findViewById<EditText>(R.id.et_code)

        //1、授权页面背景
//        configBuild.setAuthLayoutResID(com.rich.oauth.R.layout.oauth_root_view);
        configBuild.setAuthContentView(contentView)


        //2、设置å状态栏颜色（系统版本5.0以上可设置）、字体颜色（系统版本6.0以上可设置黑色、白色）。
        configBuild.setStatusBar(Color.TRANSPARENT, true)
        //开启底部导航栏自适应，开启后，导航栏唤起时，授权页面元素也会对应变化；不开启自适应，自定义内容可以铺满全屏，设置状态栏透明后，可达到沉浸式显示效果，默认开启
        configBuild.setFitsSystemWindows(false)

        // 3、号码栏
        //号码栏颜色,字体大小
        configBuild.setNumberColor(Color.BLACK)
        configBuild.setNumberSize(25, true)
        //设置号码栏相对于默认位置的X轴偏移量
        configBuild.setNumberOffsetX(0)
        //设置号码栏相对于标题栏下边缘y偏移(setNumFieldOffsetY与setNumFieldOffsetY_B，二者建议只设置一个)
        configBuild.setNumberOffsetY(200)
        //设置号码栏相对于底部y偏移（setNumFieldOffsetY与setNumFieldOffsetY_B，二者建议只设置一个）
//        configBuild.setNumFieldOffsetY_B(80);


        // 4、 登录按钮
        //登陆按钮背景
        configBuild.setLoginBtnBg(R.drawable.selector_login_button)
        //登陆按钮文本
//        configBuild.setLoginBtnText("   ")

        // 登录阿牛文本字体大小
        configBuild.setLoginBtnTextSize(0)
        // 字体是否加粗
        configBuild.setLoginBtnTextBold(false)

        val logBtnWidth = 250
        val logBtnMargin = (screenWidthDP(context) - logBtnWidth) / 2

        //登陆按钮宽度（dp为单位）
        configBuild.setLoginBtnWidth(logBtnWidth)
        //登陆按钮高度（dp为单位）
        configBuild.setLoginBtnHight(45)
        //登陆按钮文本颜色
        configBuild.setLoginBtnTextColor(-0x1000000)
        //设置登录按钮相对于底部y偏移
//        configBuild.setLogBtnOffsetY_B(200);
        //设置登录按钮相对于状态栏下边缘y偏移
        configBuild.setLogBtnOffsetY(330)
        //设置登录按钮相对于屏幕左右边缘边距
        configBuild.setLogBtnMarginLeft(logBtnMargin)
        //设置登录按钮相对于屏幕左右边缘边距
        configBuild.setLogBtnMarginRight(logBtnMargin)


        // 5.1、隐私协议
        // 协议框是否勾选
        configBuild.setProtocolSelected(false)
        configBuild.setUnCheckWay(AuthConstants.AUTHUNCHECKWAY_SECONDAUTHDIALOG)
        configBuild.setCheckTipText("请勾选同意服务条款")

        //新增协议，协议名称及协议点击地址 ,“名字设置为服务条款会出错，等待移动sdk改善”
        var link1 = "https://static.ichibankuji.cn/html/user_protocol.html";
        var link2 = "https://static.ichibankuji.cn/html/privacy_policy.html";
        if(appName == "入魂大集"){
            link1 = "https://static.ichibankuji.cn/html/daji/user_protocol.html";
            link2 = "https://static.ichibankuji.cn/html/daji/privacy_policy.html";
        }
        configBuild.setProtocol("使用协议", link1)
        configBuild.setSecondProtocol("隐私政策", link2)
//        configBuild.setSecondProtocol("腾讯sdk", "https://www.baidu.com/")
        // 设置协议内容，备注：协议内容需包含上面设置的协议名称
        configBuild.setPrivacyContentText("我已认真阅读并同意${appName}使用协议、隐私政策和\$\$运营商条款\$\$")
        // 是否设置书名号
        configBuild.setPrivacyBookSymbol(true)
        //设置协议勾选框+协议文本的抖动动画效果，默认无抖动。
        configBuild.setPrivacyAnimationBoolean(true)
        //        configBuild.setPrivacyAnimation("umcsdk_anim_shake");
        // 协议字体颜色，第一个参数为协议颜色，第二个为协议其他字体颜色
        configBuild.setPrivacyColor(Color.RED, Color.BLACK)
        //设置隐私条款相对于标题栏下边缘y偏移
        configBuild.setPrivacyOffsetY(440)
//        //设置隐私条款相对于底部y偏移
//        configBuild.setPrivacyOffsetY_B(35)
        //设置隐私条款距离手机左右边缘的边距
        configBuild.setPrivacyMarginLeft(20)
        //设置隐私条款距离手机左右边缘的边距
        configBuild.setPrivacyMarginRight(20)
        //设置隐私条款的字体大小
        configBuild.setPrivacyTextSize(13)
        //设置隐私条款的字体基本颜色：灰色
        configBuild.setClauseBaseColor(-0x99999a)
        //设置隐私条款的字体突出颜色：蓝色
        configBuild.setClauseColor(-0xff7a30)
        //设置隐私条款的字体是否居中
        configBuild.setIsGravityCenter(false)

        //设置隐私条款勾选框是否居中，0表示居上，1为居中
        configBuild.setCheckBoxLocation(0)
        //设置隐私条款勾选框宽度,单位：dp
        configBuild.setCheckBoxImageWidth(20)
        //设置隐私条款勾选框高度,单位：dp
        configBuild.setCheckBoxImageheight(20)
//        configBuild.setCheckBoxImgName("umcsdk_check_image", "umcsdk_uncheck_image");


        // 5.2、隐私协议页面部分设置
        //设置隐私协议页面服务条款标题栏背景颜色
        configBuild.setPrivacyNavBgColor(-0xffff01)
        //设置隐私协议页面服务条款标题字体颜色
        configBuild.setPrivacyNavTextColor(-0xffff01)
        //设置隐私协议页面服务条款标题字体大小
        configBuild.setPrivacyNavTextSize(15)
        // 设置隐私协议页面标题栏
        configBuild.setPrivacyNavReturnBackClauseLayoutResID(R.layout.title_layout)


//        // 6、是否设置窗口模式
//        configBuild
//            .setAuthPageWindowMode(true)
//                .setAuthPageWindowWith(screenWidthDP(context)) //设置授权页窗口宽高比例
//                .setAuthPageWindowHight(screenHeightDP(context)) //设置授权页窗口宽高比例
//                .setAuthPageWindowOffsetX(0) //设置授权页窗口X轴偏移
//                .setAuthPageWindowOffsetY(0) //设置授权页窗口Y轴偏移
//                .setAuthPageWindowThemeId(R.style.loginDialog)//设置授权页弹窗主题
//                .setAuthPageWindowBottom(0)
//                .setBackButton(true);//弹窗授权页模式下，设置物理返回键是否有效，        默认有效。true=有效，false=无效。


        //  7、登录页面进出场动画
        configBuild.setAuthPageActIn(
                "in_activity",
                "out_activity"
        ) // 设置进入一键登录页面进场动画,in_activity,out_activity为资源文件中anim动画文件名字
        configBuild.setAuthPageActOut("in_activity", "out_activity") // 设置进入一键登录页面退出动画


        //  8、其他，如授权页获取token后是否主动关闭授权页,默认为true；
        configBuild.setAutoClosAuthPage(true)
        //授权页语言切换 0.中文简体 1.中文繁体 2.英文
        configBuild.setAppLanguageType(0)


        // 一键登录页面 协议勾选框实时监听回调。
        configBuild.setOnCheckboxCheckedChange(object : CheckboxCheckedChangeListener {
            override fun onCheckboxCheckedChange(isChecked: Boolean) {
                RichLogUtil.e(javaClass.name, isChecked)
            }
        })

        // 一键登录页面 未勾选协议时 点击登录按钮 监听回调
        configBuild.setCheckboxUnCheckedClickListener(object : CheckboxUnCheckedClickListener {
            override fun onCheckboxChecked(context: Context, jsonObject: JSONObject) {
                RichLogUtil.e(javaClass.name, false)
            }
        })

        // 一键登录页面 未勾选协议时，二次弹窗确认监听
        configBuild.setUncheckDialogAuthLoginListener { contextTemp, callBack -> showPrivacyAlertDialog(contextTemp, callBack) }


        val uiConfig = configBuild.build()
        RichAuth.getInstance().login(context, uiConfig, object : TokenCallback {
            override fun onTokenSuccessResult(token: String, carrier: String) {
                //成功获取token，运营商，可通过此token获取号码,
                RichLogUtil.e("token:$token")
//                Toast.makeText(this@MainActivity, "token获取成功:$token", Toast.LENGTH_SHORT).show()

                val inviteCode = if (inputCode == null) "" else inputCode.text
                channel.invokeMethod(
                        "getToken",
                        hashMapOf(
                                Pair("loginResultCode", "0"),
                                Pair("carrier", carrier),
                                Pair("token", token),
                                Pair("inviteCode", inviteCode)
                        )
                )
            }

            override fun onTokenFailureResult(error: String) {
                // 获取失败信息
                RichLogUtil.e("onTokenFailureResult$error")
                channel.invokeMethod(
                        "getToken",
                        hashMapOf(
                                Pair("loginResultCode", "-1"),
                                Pair("resultMsg", "获取token失败"),
                        )
                )
//                mMainTokenTv.setText("token获取失败:$error")
//                Toast.makeText(this@MainActivity, "获取失败:$error", Toast.LENGTH_SHORT).show()
            }
//
//            override fun onCheckboxCheckedChange(p0: Boolean) {
//                RichLogUtil.e("onCheckboxCheckedChange")
//            }
//
//            override fun onAuthLoginListener(p0: Context?) {
//                RichLogUtil.e("onAuthLoginListener")
//            }
//
//            override fun onPressBackListener(p0: Context?) {
//                RichLogUtil.e("返回按钮点击回调")
//            }
//
//            override fun onCheckboxChecked(context: Context, jsonObject: JSONObject) {
//                RichLogUtil.e("设置授权页勾选框和登录按钮的监听事件")
//            }
//
//            override fun onLoginClickComplete(context: Context, jsonObj: JSONObject) {
//                //登录按钮点击监听事件
//                RichLogUtil.e("onLoginClickComplete")
//            }
//
//            override fun onLoginClickStart(context: Context, jsonObj: JSONObject) {
//                //登录按钮点击监听事件
//                RichLogUtil.e("onLoginClickStart")
//            }
        })
    }

    private fun showPrivacyAlertDialog(context: Context, callBack: AuthLoginCallBack?) {
//        authLoginCallBack = callBack
//        channel.invokeMethod(
//                "unCheckDialog",
//                ""
//        )

        OperatorAgreementDialog.show(context) {
            title = "协议确认"
            content = "使用前请您仔细阅读并同意以下协议${termsKeyword}、${privacyKeyword}和${carrierKeyword}。"
            agreeText = "同意并继续"
            disagreeText = "取消"
            onAgree = {
                // 用户点击同意后的处理
                callBack?.onAuthLoginCallBack(true)
            }

            onDisagree = {
                // 用户拒绝后的处理
            }

            onTermsClick = {
                val intent = Intent(context, PrivacyWebViewActivity::class.java).apply {
                    putExtra("url", "https://static.ichibankuji.cn/html/user_protocol.html")
                }
                startActivity(context, intent, null)
            }

            onPrivacyClick = {
                val intent = Intent(context, PrivacyWebViewActivity::class.java).apply {
                    putExtra("url", "https://static.ichibankuji.cn/html/privacy_policy.html")
                }
                startActivity(context, intent, null)
            }

            onCarrierClick = {
                // 跳转隐私政策页
                if (carrier == null) {
                    carrier = RichAuth.getInstance().getOperatorType(context)
                }
                var carrierUrl = ""
                when (carrier) {
                    "1" -> carrierUrl = "https://wap.cmpassport.com/resources/html/contract.html"
                    "2" -> carrierUrl = "https://auth.wosms.cn/html/oauth/protocol3.html?top=true&darkMode=true"
                    "3" -> carrierUrl = "https://e.189.cn/sdk/agreement/detail.do?appKey=E_189&hidetop=true&returnUrl="
                }
                if (carrierUrl.isNotEmpty()) {
                    val intent = Intent(context, PrivacyWebViewActivity::class.java).apply {
                        putExtra("url", carrierUrl)
                    }
                    startActivity(context, intent, null)
                }
            }
        }
    }

    private fun getMap(jsonString: String?): Map<String, Any> {
        val jsonObject: JSONObject
        try {
            jsonObject = JSONObject(jsonString)
            val keyIter: Iterator<String> = jsonObject.keys()
            var key: String
            var value: Any
            val valueMap = HashMap<String, Any>()
            while (keyIter.hasNext()) {
                key = keyIter.next()
                value = jsonObject[key] as Any
                valueMap[key] = value
            }
            return valueMap
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        return emptyMap()
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
        context = null
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        activity = binding.activity
    }

    override fun onDetachedFromActivityForConfigChanges() {
        activity = null
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        activity = binding.activity
    }

    override fun onDetachedFromActivity() {
        activity = null
    }
}
